﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using H2.NET.Common;

namespace H2.NET.Web.Workflow
{
    public partial class Complete2 : System.Web.UI.Page
    {
        [SessionType]
        public clsCommon clsCmm = new clsCommon();

        [SessionType]
        string strProcessName = "";

        string strType = "";
        string[] strRange = new string[2] {"", ""};

        #region 事件 页面 加载
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Response.Buffer = true;
                Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
                Response.Expires = 0;
                Response.CacheControl = "no-cache";                

                //如果是超时以及未登陆系统的情况
                if (!clsCmm.isLogin(User.Identity.Name, User.Identity.AuthenticationType))
                {
                    string strUserName = Request.QueryString["UserName"];
                    if (string.IsNullOrEmpty(strUserName) || Util.Decode(strUserName).IndexOf('/') == -1)
                    {
                        //转入登陆界面
                        Response.Write(Util.GoToWebPath(ResolveUrl("~/logon.aspx")));
                    }
                    else
                    {
                        clsCmm.chkLogin(Util.Decode(strUserName));
                    }  
                }

                //added by 
                strProcessName = Request.QueryString["process"];
                strType        = Request.QueryString["type"];

                //第一次加载页面时初始化
                if (!Page.IsPostBack)
                {
                    //语言设置
                    btnSearch.Text = clsCmm.getTextValue("frm_inbox_btnSearch");
                    lblSearch.Text = clsCmm.getTextValue("frm_initiate_txtSearch");
                    e_element_tr_search.Value = "none";

                    //查询并对列表进行数据绑定
                    load_rep_group_list();
                }
            }
            catch
            {
                //TaskDB.Log("", false, "调用 inbox.aspx 页面 Page_Load 事件出错：" + ee.Message);
            }
        }
        #endregion

        #region 事件 单击 Search 按钮
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                foreach(RepeaterItem ri in gvComplete.Items)
                {
                    ImageButton imgG = ri.FindControl("imgGroup") as ImageButton;
                    Repeater rpt = ri.FindControl("dv_show") as Repeater;
                    strRange = imgG.CommandArgument.ToString().Split('~');

                    if (imgG.CommandName == "Shrink")
                    {
                        load_gv_complete_list(rpt);
                    }
                }
            }
            catch
            {
                //TaskDB.Log("", false, "调用 complete.aspx 页面 btnSearch_Click 事件出错：" + ee.Message);
            }
        }
        #endregion

        #region 事件 显示/隐藏 Search 条件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void img_btn_Search_Click(object sender, ImageClickEventArgs e)
        {
            //显示查询条件选择框
            set_e_element_tr_search_show();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lblSearch_Click(object sender, EventArgs e)
        {
            //显示查询条件选择框
            set_e_element_tr_search_show();
        }
        #endregion

        #region 事件 明细行命令
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvComplete_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName != "Expand" && e.CommandName != "Shrink")
            {
                return;
            }

            //如果是行命令的情况
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                strRange = e.CommandArgument.ToString().Split('~');
                ImageButton imgG = e.Item.FindControl("imgGroup") as ImageButton;
                Repeater rpt = e.Item.FindControl("dv_show") as Repeater;

                if (imgG.CommandName == "Expand")
                {
                    load_gv_complete_list(rpt);
                    rpt.Visible = true;
                }
                else
                {
                    rpt.Visible = false;
                }

                imgG.CommandName = imgG.CommandName == "Expand" ? "Shrink" : "Expand";
                imgG.ImageUrl = imgG.CommandName == "Expand" ? "~/Resource/Images/cmm_dot_shrink.gif" : "~/Resource/Images/cmm_dot_expand.gif";
            }
        }
        #endregion

        #region 方法 获取完成箱列表
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public DataTable get_all_complete()
        {
            try
            {
                string strSQL = "";
                string strUserName = clsCmm.comm_username;
                string strSummary = txtSummary.Text.Trim().Replace(",", "',").Replace("'", "''");
                string strIncidentNoFrom = txtIncidentFrom.Text.Trim().Replace(".", "");
                string strIncidentNoTo = txtIncidentTo.Text.Trim().Replace(".", "");

                //查询过滤中Process下拉列表中的值
                string strProcess = "all";
                if (drpProcess.SelectedItem != null)
                {
                    strProcess = drpProcess.SelectedItem.Value.Trim();
                }

                //string strStep = "all";
                //if (drpStep.SelectedItem != null)
                //{
                //    strStep = drpStep.SelectedItem.Value.Trim();
                //}

                //查找收件箱列表
                strSQL = "";
                strSQL += "select distinct d.*,";
                strSQL += " '' as initiator_name,";
                strSQL += " '' as taskuser_name,";
                strSQL += " '' as assignedtouser_name";
                strSQL += "  from (select b.*, c.summary, c.priority, c.initiator";
                strSQL += "  from (select rtrim(a.taskid) as taskid";
                //中文的情况，流程名变化
                if (clsCmm.comm_language == "en-us" && Util.AppSettings("language").ToLower() == "yes")
                {
                    strSQL += " ,h.processhelpurl as processname3";
                    strSQL += " ,h.processname";
                }
                else
                {
                    strSQL += " ,a.processname as processname3";
                    strSQL += " ,a.processname";
                }

                strSQL += " ,rtrim(a.helpurl) as helpurl";
                strSQL += " ,'' as openform";

                strSQL += " ,a.incident";
                strSQL += " ,a.steplabel";
                strSQL += " ,a.taskuser";
                strSQL += " ,a.assignedtouser";
                strSQL += " ,'' as img_status";     //状态图标
                strSQL += " ,'' as img_monitor";    //监控图标
                strSQL += " ,a.status";
                strSQL += " ,a.substatus";
                strSQL += " ,a.starttime";
                strSQL += " ,a.endtime";
                strSQL += " ,a.delaytime";
                strSQL += " ,a.overduetime";
                strSQL += " ,a.urgentduetime";

                #region 查询字段(暂时不用)
                //strSQL += "                    ,a.qstarttime,";
                //strSQL += "                    ,a.qendtime,";
                //strSQL += "                    ,a.recipienttype";
                //strSQL += "                    ,a.recipient";
                //strSQL += "                    ,a.stepid";
                //strSQL += "                    ,a.processversion";
                //strSQL += "                    ,a.taskrate";
                //strSQL += "                    ,a.tasktime";
                //strSQL += "                    ,a.cost";
                #endregion

                strSQL += " from tasks a, initiate h";
                strSQL += " where a.processname=h.processname and lower(a.assignedtouser) = lower('" + strUserName + "')";
                strSQL += " and a.status in(3,7)";
                //strSQL += " and a.substatus in (0,1,2,4)";
                strSQL += " and a.endtime >='" + strRange[0] + "'";
                strSQL += " and a.endtime <'" + strRange[1] + "'";

                //查询过滤
                if (strProcess != "all")
                {
                    strSQL = strSQL + " and a.processname = '" + strProcess + "'";
                }

                //added by
                if (!string.IsNullOrEmpty(strProcessName))
                {
                    strSQL = strSQL + " and a.processname = '" + strProcessName + "'";
                } 

                //if (strStep != "all")
                //{
                //    strSQL = strSQL + " and a.steplabel = '" + strStep + "'";
                //}

                if (strIncidentNoFrom != "")
                {
                    strSQL = strSQL + " and a.incident >= " + strIncidentNoFrom + "";
                }

                if (strIncidentNoTo != "")
                {
                    strSQL = strSQL + " and a.incident <= " + strIncidentNoTo + "";
                }

                strSQL += " ) b";
                strSQL += " left join incidents c on b.processname = c.processname and b.incident = c.incident) d";

                //摘要
                if (strSummary != "")
                {
                    strSQL = strSQL + " where d.summary like '%" + strSummary + "%'";
                }

                TaskDB.Log("", true, "调用 inbox.aspx 页面 get_all_complete 方法SQL：" + strSQL);

                clsCmm.clsDB.Storage("bpmDB");
                DataTable dt = clsCmm.clsDB.Query(strSQL);

                //在没有结果返回的情况，返回一空白行
                if (dt.Rows.Count == 0)
                {
                    DataRow dr = dt.NewRow();
                    dt.Rows.Add(dr);
                }

                return dt;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region 方法 查询分组列表并进行数据绑定
        /// <summary>
        /// 
        /// </summary>
        public void load_rep_group_list()
        {
            try
            {
                strType = string.IsNullOrEmpty(strType) ? "1" : strType;

                //加载列表
                DataTable dt = new DataTable();
                dt.Clear();

                dt.Columns.Add("Title");
                dt.Columns.Add("Range");

                //按周进行统计
                if(strType == "1")
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = clsCmm.getTextValue("frm_complete_grp_today");
                    dr[1] = System.DateTime.Today.ToString("yyyy-MM-dd") + "~" + System.DateTime.Today.AddDays(1).ToString("yyyy-MM-dd");
                    dt.Rows.Add(dr);

                    DataRow dr2 = dt.NewRow();
                    dr2[0] = clsCmm.getTextValue("frm_complete_grp_yesterday");
                    dr2[1] = System.DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd") + "~" + System.DateTime.Today.ToString("yyyy-MM-dd");
                    dt.Rows.Add(dr2);

                    if (System.DateTime.Today.DayOfWeek != DayOfWeek.Monday && System.DateTime.Today.DayOfWeek != DayOfWeek.Tuesday)
                    {
                        DataRow dr3 = dt.NewRow();
                        dr3[0] = clsCmm.getTextValue("frm_complete_grp_week");
                        dr3[1] = System.DateTime.Today.AddDays(-1*(System.DateTime.Today.DayOfWeek == DayOfWeek.Sunday ? 6 : (int)System.DateTime.Today.DayOfWeek - 1)).ToString("yyyy-MM-dd") + "~" + System.DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
                        dt.Rows.Add(dr3);
                    }

                    DataRow dr4 = dt.NewRow();
                    dr4[0] = clsCmm.getTextValue("frm_complete_grp_last_week");
                    dr4[1] = System.DateTime.Today.AddDays((-1 * (System.DateTime.Today.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)System.DateTime.Today.DayOfWeek))-6).ToString("yyyy-MM-dd") + "~" + System.DateTime.Today.AddDays((-1 * (System.DateTime.Today.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)System.DateTime.Today.DayOfWeek)) + 1).ToString("yyyy-MM-dd");
                    dt.Rows.Add(dr4);

                    DataRow dr5 = dt.NewRow();
                    dr5[0] = clsCmm.getTextValue("frm_complete_grp_2_week_ago");
                    dr5[1] = System.DateTime.Today.AddDays((-1 * (System.DateTime.Today.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)System.DateTime.Today.DayOfWeek)) - 13).ToString("yyyy-MM-dd") + "~" + System.DateTime.Today.AddDays((-1 * (System.DateTime.Today.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)System.DateTime.Today.DayOfWeek)) - 6).ToString("yyyy-MM-dd");
                    dt.Rows.Add(dr5);

                    DataRow dr6 = dt.NewRow();
                    dr6[0] = clsCmm.getTextValue("frm_complete_grp_earlier");
                    dr6[1] = "2000-01-01" + "~" + System.DateTime.Today.AddDays((-1 * (System.DateTime.Today.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)System.DateTime.Today.DayOfWeek)) - 13).ToString("yyyy-MM-dd");
                    dt.Rows.Add(dr6);
                }

                //按月进行统计
                if (strType == "2")
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = clsCmm.getTextValue("frm_complete_grp_this_month");
                    dr[1] = System.DateTime.Today.ToString("yyyy-MM") + "-1" + "~" + System.DateTime.Today.AddDays(1).ToString("yyyy-MM-dd");
                    dt.Rows.Add(dr);

                    DataRow dr2 = dt.NewRow();
                    dr2[0] = clsCmm.getTextValue("frm_complete_grp_last_month");
                    dr2[1] = System.DateTime.Today.AddMonths(-1).ToString("yyyy-MM") + "-1" + "~" + System.DateTime.Today.ToString("yyyy-MM") + "-1";
                    dt.Rows.Add(dr2);

                    DataRow dr3 = dt.NewRow();
                    dr3[0] = clsCmm.getTextValue("frm_complete_grp_earlier");
                    dr3[1] = "2000-01-01" + "~" + System.DateTime.Today.AddMonths(-1).ToString("yyyy-MM") + "-1";
                    dt.Rows.Add(dr3);
                }

                gvComplete.DataSource = dt;
                gvComplete.DataBind();
            }
            catch
            {
                //TaskDB.Log("", false, "调用 complete.aspx 页面 load_gv_complete_list方法出错：" + ee.Message);
            }
        }
        #endregion

        #region 方法 查询并对列表进行数据绑定
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void load_gv_complete_list(Repeater rep)
        {
            try
            {
                //加载列表
                DataTable dt = get_all_complete();

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region added by zk 2009-12-21 start
                //取得所有的用户账号对应用户姓名             
                string str_user_name = "";
                DataTable dt2 = new DataTable();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //initiator
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'";
                    }

                    //taskuser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'";
                    }

                    //assignedtouser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'";
                    }
                }

                //从数据库中查询用户信息
                string strSQL = "select rtrim(FULLNAME) as UserFullName,lower(rtrim(Name)) as UserShortName from JOBS where lower(rtrim(Name)) in('-1'" + str_user_name + ")";
                clsCmm.clsDB.Storage("bpmDB");
                dt2 = clsCmm.clsDB.Query(strSQL);
                #endregion added by zk 2009-12-21 end

                //设置状态列的图片
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //处理表单类型 (自定义表单 & 标准表单)
                    string HelpUrl = dt.Rows[i]["helpurl"].ToString();
                    if (!string.IsNullOrEmpty(HelpUrl) && HelpUrl.Length >= 5 && HelpUrl.Substring(0, 5).ToLower() == "form:")
                    {
                        dt.Rows[i]["openform"] = HelpUrl.Substring(5, HelpUrl.Length - 5);
                    }
                    else
                    {
                        dt.Rows[i]["openform"] = "openform.aspx";
                    }

                    #region added by zk 2009-12-21 start
                    //循环设置用户信息
                    for (int j = 0; j < dt2.Rows.Count; j++)
                    {
                        //initiator
                        if (dt.Rows[i]["initiator"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["initiator_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //taskuser
                        if (dt.Rows[i]["taskuser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["taskuser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //assignedtouser
                        if (dt.Rows[i]["assignedtouser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["assignedtouser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }
                    }
                    #endregion added by zk 2009-12-21 end

                    //如果是被 Cancel 的情况
                    if (dt.Rows[i]["status"].ToString().Trim() == "7")
                    {
                        dt.Rows[i]["img_status"] = "frm_inbox_aborted.gif";
                    }
                    else
                    {
                        //流程状态图标
                        switch (dt.Rows[i]["substatus"].ToString().Trim())
                        {
                            case "0":
                                dt.Rows[i]["img_status"] = "frm_complete_pending.gif";
                                break;

                            case "1":
                                dt.Rows[i]["img_status"] = "frm_complete_pending.gif";
                                break;

                            case "2":
                                dt.Rows[i]["img_status"] = "frm_complete_pending.gif";
                                break;

                            case "4":
                                dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                                break;

                            case "8":
                                dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                                break;

                            case "12":
                                dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                                break;

                            case "16":
                                dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                                break;

                            default:
                                dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                                break;
                        }
                    }

                    //是否显示监控图标
                    if (dt.Rows[i]["taskid"] == DBNull.Value || dt.Rows[i]["taskid"].ToString().Trim() == "")
                    {
                        dt.Rows[i]["img_monitor"] = "frm_initiate_blank.gif";
                        dt.Rows[i]["img_status"]  = "frm_initiate_blank.gif";
                    }
                    else
                    {
                        dt.Rows[i]["img_monitor"] = "bpmview.gif";
                    }
                }

                //第一次没有排序字段的情况
                if (ViewState["OrderBy"] == null)
                {
                    dt.DefaultView.Sort = "status DESC, starttime DESC";
                }
                else
                {
                    dt.DefaultView.Sort = ViewState["OrderBy"] + " " + ViewState["Order"];
                }

                rep.DataSource = dt;
                rep.DataBind();

                //加载列表框
                load_drp_control_list(dt);
            }
            catch
            {
                //TaskDB.Log("", false, "调用 complete.aspx 页面 load_gv_complete_list方法出错：" + ee.Message);
            }
        }
        #endregion

        #region 方法 查询并对查询下拉列表进行填充
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void load_drp_control_list(DataTable dt)
        {
            try
            {
                //增加第一行
                if (drpProcess.Items.Count == 0)
                {
                    drpProcess.Items.Add(new ListItem("All", "all"));
                }
                //drpStep.Items.Add(new ListItem("All", "all"));

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                //循环所有的记录集
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    bool Flg = false;

                    //流程名称下拉列表
                    if(!string.IsNullOrEmpty(dt.Rows[i]["processname"].ToString()))
                    {
                        Flg = true;

                        foreach (ListItem item in drpProcess.Items)
                        {
                            if (dt.Rows[i]["processname"].ToString() == item.Value)
                            {
                                Flg = false;
                                break;
                            }
                        }
                    }

                    ////步骤名称下拉列表
                    //foreach (ListItem item in drpStep.Items)
                    //{
                    //    if (dt.Rows[i]["steplabel"].ToString() == item.Value)
                    //    {
                    //        Flg2 = false;
                    //        break;
                    //    }
                    //}

                    //如果不存在的情况
                    if (Flg)
                    {
                        drpProcess.Items.Add(new ListItem(dt.Rows[i]["processname"].ToString(), dt.Rows[i]["processname"].ToString()));
                    }

                    //if (Flg2)
                    //{
                    //    drpStep.Items.Add(new ListItem(dt.Rows[i]["steplabel"].ToString(), dt.Rows[i]["steplabel"].ToString()));
                    //}
                }
            }
            catch
            {
                //TaskDB.Log("", false, "调用 complete.aspx 页面 load_drp_control_list方法出错：" + ee.Message);
            }
        }
        #endregion

        #region 方法 设置 Serach 条件 可见
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void set_e_element_tr_search_show()
        {
            try
            {
                if (e_element_tr_search.Value == "none")
                {
                    e_element_tr_search.Value = "block";
                }
                else
                {
                    e_element_tr_search.Value = "none";
                }
            }
            catch
            {
                //TaskDB.Log("", false, "调用 inbox.aspx 页面 set_e_element_tr_search_show方法出错：" + ee.Message);
            }
        }
        #endregion
    }
}
